package com.lastproject.web.bean;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import com.lastproject.dto.EmailGroupDTO;
import com.lastproject.dto.QuestionDTO;
import com.lastproject.dto.QuestionOptionDTO;
import com.lastproject.dto.SurveyDTO;
import com.lastproject.dto.UserDTO;
import com.lastproject.ejb.dao.EmailGroupDAORemote;
import com.lastproject.ejb.dao.QuestionDAORemote;
import com.lastproject.ejb.dao.QuestionOptionDAORemote;
import com.lastproject.ejb.dao.SurveyDAORemote;
import com.lastproject.ejb.timers.TimerBeanRemote;
import com.lastproject.service.MailSenderRemote;

public class SurveyCreateBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1077573067139602578L;

	private boolean hasQuestions;

	private boolean succes = false;

	private boolean finished = false;

	private boolean addNewQuestion = false;

	private boolean addNewQuestionOption = false;

	private String question;

	private String type;

	private String optionText;

	private String textDefault;

	private String group;

	private List<QuestionOptionDTO> questionOptionList;

	private List<QuestionDTO> questionList;

	private List<QuestionDTO> questions = new ArrayList<QuestionDTO>();

	@EJB
	SurveyDAORemote surveyDAORemote;

	@EJB
	QuestionDAORemote questionDAORemote;

	@EJB
	QuestionOptionDAORemote questionOptionDAORemote;

	@EJB
	MailSenderRemote mailSenderRemote;

	@EJB
	EmailGroupDAORemote emailGroupDAORemote;

	@EJB
	TimerBeanRemote timerBeanRemote;

	private SurveyDTO surveyDTO;

	private QuestionDTO questionDTO;

	private QuestionOptionDTO questionOptionDTO;

	private EmailGroupDTO emailGroupDTO;

	private List<EmailGroupDTO> emailGroups;

	public SurveyCreateBean() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * Create a questionOption
	 * 
	 * @return Returns a String containing [nextPage].xhtml
	 */
	public String createQuestionOption() {

		surveyDTO.setTitle("");
		surveyDTO.setDescription("");
		surveyDTO.setEndDate(null);

		surveyDTO = surveyDAORemote.findLastByMe(surveyDTO.getIdUser());

		if (questionDAORemote.findLastByTextAndSurvey(question, surveyDTO) == null) {
			createQuestion();
		}

		questionDTO = questionDAORemote.findLastByText(question);

		questionOptionDTO = new QuestionOptionDTO();

		questionOptionDTO.setQuestionId(questionDTO.getId());
		questionOptionDTO.setText(optionText);
		questionOptionDTO.setTextDefault(textDefault);
		questionOptionDTO.setType(type);

		questionOptionDAORemote.create(questionOptionDTO);
		questions.get(questions.size() - 1).getOptions().add(questionOptionDTO);
		resetFields();
		hasQuestions = true;
		return "";
	}

	/**
	 * Create a new Question
	 * 
	 * @return Returns a String containing [nextPage].xhtml
	 */
	public String createQuestion() {
		questionDTO = new QuestionDTO();
		questionDTO.setSurveyId(surveyDTO.getId());
		questionDTO.setText(question);

		questionDAORemote.create(questionDTO);

		questions.add(questionDTO);
		questions.get(questions.size() - 1).setOptions(
				new ArrayList<QuestionOptionDTO>());

		return "";
	}

	/**
	 * Reset the fields on the .xhtml page
	 * 
	 * @return Returns a String containing [nextPage].xhtml
	 */
	public String done() {
		resetFields();
		setQuestion("");
		setAddNewQuestion(false);
		return "";
	}

	/**
	 * Send an e-mail to destination group
	 * 
	 * @return Returns a String containing [nextPage].xhtml
	 */
	public String send() {

		if (hasQuestions == true) {

			emailGroupDTO = emailGroupDAORemote.findByID(Integer
					.parseInt(group));
			surveyDTO.setEmailGroup(emailGroupDTO);
			surveyDTO.setFinished(true);
			surveyDAORemote.edit(surveyDTO);
			for (UserDTO u : emailGroupDTO.getUsers()) {
				sendMail(u.getWorkEmail());
			}
			questions = new ArrayList<QuestionDTO>();
			question = "";
			addNewQuestion = false;

			Calendar today = Calendar.getInstance();
			today.setTime(new Date());
			Calendar endDate = Calendar.getInstance();
			endDate.setTime(surveyDTO.getEndDate());

			timerBeanRemote.startTimer("surveyTimer_" + surveyDTO.getId(),
					endDate.getTimeInMillis() - today.getTimeInMillis()
							- 86400000);
			hasQuestions = false;
			return "surveyFinished.xhtml";
		}
		else{
			
			return "survey.xhtml";
		}
	}

	/**
	 * Send an e-mail to an e-mail address
	 * 
	 * @param receiver
	 *            The destination e-mail address
	 */
	public void sendMail(String receiver) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String subject = "New survey!";
		String content = "Survey title: " + surveyDTO.getTitle() + ".\n"
				+ "Description: " + surveyDTO.getDescription() + ".\n"
				+ "Start date: " + sdf.format(surveyDTO.getStartDate())
				+ ", End date: " + sdf.format(surveyDTO.getEndDate()) + ".";
		String sender = "peterjozsi@gmail.com";
		surveyDTO.setFinished(true);
		mailSenderRemote.sendMail(sender, receiver, subject, content);
	}

	/**
	 * Validate if e-mail address is correct
	 * 
	 * @param email
	 *            Parameter containing the introduced e-mail address
	 * @return Returns a boolean containing the result of validation
	 */
	public boolean isValidEmailAddress(String email) {
		boolean result = true;
		try {
			InternetAddress emailAddr = new InternetAddress(email);
			emailAddr.validate();
		} catch (AddressException ex) {
			result = false;
		}
		return result;
	}

	/**
	 * Reset fields on .xhtml page
	 */
	public void resetFields() {
		optionText = "";
		textDefault = "";
		addNewQuestionOption = false;
	}

	public String getQuestion() {
		return question;
	}

	public void setQuestion(String question) {
		this.question = question;
	}

	public boolean isAddNewQuestion() {
		return addNewQuestion;
	}

	public void setAddNewQuestion(boolean addNewQuestion) {
		this.addNewQuestion = addNewQuestion;
	}

	public boolean isAddNewQuestionOption() {
		if (addNewQuestion == false)
			return false;
		return addNewQuestionOption;
	}

	public void setAddNewQuestionOption(boolean addNewQuestionOption) {
		this.addNewQuestionOption = addNewQuestionOption;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public SurveyDTO getSurveyDTO() {
		return surveyDTO;
	}

	public void setSurveyDTO(SurveyDTO surveyDTO) {
		this.surveyDTO = surveyDTO;
	}

	public String getOptionText() {
		return optionText;
	}

	public void setOptionText(String optionText) {
		this.optionText = optionText;
	}

	public String getTextDefault() {
		return textDefault;
	}

	public void setTextDefault(String textDefault) {
		this.textDefault = textDefault;
	}

	public QuestionDTO getQuestionDTO() {
		return questionDTO;
	}

	public void setQuestionDTO(QuestionDTO questionDTO) {
		this.questionDTO = questionDTO;
	}

	public QuestionOptionDTO getQuestionOptionDTO() {
		return questionOptionDTO;
	}

	public void setQuestionOptionDTO(QuestionOptionDTO questionOptionDTO) {
		this.questionOptionDTO = questionOptionDTO;
	}

	public List<QuestionOptionDTO> getQuestionOptionList() {
		return questionOptionList;
	}

	public void setQuestionOptionList(List<QuestionOptionDTO> questionOptionList) {
		this.questionOptionList = questionOptionList;
	}

	public List<QuestionDTO> getQuestionList() {
		return questionList;
	}

	public void setQuestionList(List<QuestionDTO> questionList) {
		this.questionList = questionList;
	}

	public String getGroup() {
		return group;
	}

	public void setGroup(String group) {
		this.group = group;
	}

	public EmailGroupDTO getEmailGroupDTO() {
		return emailGroupDTO;
	}

	public void setEmailGroupDTO(EmailGroupDTO emailGroupDTO) {
		this.emailGroupDTO = emailGroupDTO;
	}

	public List<EmailGroupDTO> getEmailGroups() {
		return emailGroupDAORemote.findAll();
	}

	public void setEmailGroups(List<EmailGroupDTO> emailGroups) {
		this.emailGroups = emailGroups;
	}

	public List<QuestionDTO> getQuestions() {
		return questions;
	}

	public void setQuestions(List<QuestionDTO> questions) {
		this.questions = questions;
	}

	public boolean isSucces() {
		return succes;
	}

	public void setSucces(boolean succes) {
		this.succes = succes;
	}

	public boolean isFinished() {
		return finished;
	}

	public void setFinished(boolean finished) {
		this.finished = finished;
	}

	public boolean isHasQuestions() {
		return hasQuestions;
	}

	public void setHasQuestions(boolean hasQuestions) {
		this.hasQuestions = hasQuestions;
	}
}
